package com.doubi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.doubi.entity.Tagtable;
import com.doubi.service.TagtableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
public class TagtableConteoller {
    @Autowired
    private TagtableService tagtableService;
    /**
     * 查询所有标签
     */
    @GetMapping("AllTags")
    public Object getAllTags() {
        return tagtableService.list();
    }
    /**
     * 模糊查询标签
     */
    @GetMapping("selectLikeTag")
    public List<Tagtable> selectLikeTag(String currentChar) {
        QueryWrapper<Tagtable> wrapper = new QueryWrapper<>();
        wrapper.like("tagContent", currentChar);
        return tagtableService.list(wrapper);
    }
    /**
     *添加新标签
     */
    @PostMapping("addtag")
    public Object addTag(@RequestBody Map<String, Object> obj) {
        Object addtagList = obj.get("addtagList");
        List<String> list = (List<String>) addtagList;
        boolean flag = false;
        for (int i = 0; i < list.size(); i++) {
            //查询是否存在此标签
            Integer count = tagtableService.iftagContent(list.get(i));
            if(count>0){
                //原有标签加一次使用
                QueryWrapper<Tagtable> wrapper = new QueryWrapper<>();
                wrapper.like("tagContent", list.get(i));
                List<Tagtable> listed = tagtableService.list(wrapper);
                if(listed.size()>0){
                    //添加一次使用
                    Tagtable tagtable = listed.get(0);
                    Integer num=Integer.parseInt(tagtable.getTagNum())+1;
                    tagtable.setTagNum(num+"");
                    flag = tagtableService.updateTagNum(tagtable.getTagNum(),tagtable.getTid());
                }
            }else {
                //添加新的标签
                Tagtable tagtable = new Tagtable();
                tagtable.setTagNum("1");
                tagtable.setTagContent(list.get(i));
                flag=tagtableService.save(tagtable);
            }
        }
        return flag;
    }
}
